import React, { Component,ChangeEvent } from 'react';
import axios from 'axios';
import {RouteComponentProps} from 'react-router-dom';

interface Iprops extends RouteComponentProps{}

interface Istate{
    username:string,
    password:string,
    [propname:string]:any
}

class login extends Component<Iprops,Istate>{
    state = {
        username:'',
        password:''
    }
    render() {
        let {username,password} = this.state;
        return (
            <div>
                <div>
                    用户名：<input type="text" value={username} onChange={this.change} name="username"/>
                </div>
                <div>
                    密码：<input type="text" value={password} onChange={this.change} name="password"/>
                </div>
                <button onClick={this.login}>登录</button>
            </div>
        );
    }

    change = (e:ChangeEvent) =>{
        this.setState({
            [(e.target as HTMLInputElement).name]:(e.target as HTMLInputElement).value
        })
    }

    //登录
    login = () =>{
        let {username,password} = this.state;
        if(username && password){
            axios.post('/api/login',{username,password}).then(res => {
                if(res.data.code === 1){
                    localStorage.setItem('name',username);
                    this.props.history.push('/main/home');
                }
            })
        }
    }
}

export default login;